/**
 * 自定义图片渲染示例
 * 展示如何使用 CustomImage 类进行各种渲染效果
 */

import { fabric } from 'fabric';
import { CustomImage } from './CustomImage';

export class ImageRendererExample {
    private canvas: fabric.Canvas;

    constructor(canvas: fabric.Canvas) {
        this.canvas = canvas;
    }

    /**
     * 创建示例图片
     */
    async createExampleImage(imageUrl: string) {
        return new Promise<CustomImage>((resolve, reject) => {
            const img = new Image();
            img.crossOrigin = 'anonymous';
            img.onload = () => {
                const customImage = new (fabric as any).CustomImage(img, {
                    maskType: 'circle',
                    brightness: 0,
                    contrast: 0,
                    saturation: 0,
                    left: 100,
                    top: 100,
                    scaleX: 0.5,
                    scaleY: 0.5
                });
                resolve(customImage);
            };
            img.onerror = reject;
            img.src = imageUrl;
        });
    }

    /**
     * 演示各种遮罩效果
     */
    async demonstrateMasks(imageUrl: string) {
        const masks = ['none', 'circle', 'rect', 'triangle', 'heart', 'star'];
        
        for (let i = 0; i < masks.length; i++) {
            const image = await this.createExampleImage(imageUrl);
            image.set({
                left: 100 + (i % 3) * 200,
                top: 100 + Math.floor(i / 3) * 200
            });
            image.setMaskType(masks[i]);
            this.canvas.add(image);
        }
        
        this.canvas.renderAll();
    }

    /**
     * 演示滤镜效果
     */
    async demonstrateFilters(imageUrl: string) {
        const filters = [
            { brightness: 50, contrast: 0, saturation: 0, name: '高亮度' },
            { brightness: 0, contrast: 50, saturation: 0, name: '高对比度' },
            { brightness: 0, contrast: 0, saturation: 50, name: '高饱和度' },
            { brightness: -30, contrast: 20, saturation: -20, name: '复古效果' }
        ];

        for (let i = 0; i < filters.length; i++) {
            const image = await this.createExampleImage(imageUrl);
            image.set({
                left: 100 + (i % 2) * 300,
                top: 100 + Math.floor(i / 2) * 300
            });
            image.setImageFilters(
                filters[i].brightness,
                filters[i].contrast,
                filters[i].saturation
            );
            this.canvas.add(image);
        }
        
        this.canvas.renderAll();
    }

    /**
     * 清除画布
     */
    clearCanvas() {
        this.canvas.clear();
        this.canvas.renderAll();
    }

    /**
     * 导出画布为图片
     */
    exportCanvas() {
        return this.canvas.toDataURL({
            format: 'png',
            quality: 1,
            multiplier: 2
        });
    }
}
